import 'dart:async';

import 'package:eleapp/pages/login/login.dart';
import 'package:eleapp/res/colors.dart';
import 'package:eleapp/res/strings.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart'
    as dio_package; // 用于发请求 避免get和dio库里面都有FormData导致冲突
import 'dart:io'; // 使用File方法 解析文件本地文件，展示图片

// 控制器
import '../../controller/usercontroller.dart';
// 状态管理
import '../../localstorage/storage.dart';

import '../../ui/dialog/mydialog.dart';
import '../../dio/http_request.dart';
import '../../dio/api.dart';

import '../../util/toast_util.dart';
import '../../util/formatter/customized_length_formatter.dart';
import '../../util/formatter/customized_text_formatter.dart';

class Myinfo extends StatefulWidget {
  const Myinfo({super.key});

  @override
  State<Myinfo> createState() => _MyinfoState();
}

class _MyinfoState extends State<Myinfo> {
  // 注入提示词状态管理控制器
  UserController userController = Get.find();
  TipController tipController = Get.find();
  IconController iconController = Get.find();

  bool confirneyeExpand = true;

  final ImagePicker _imagePicker = ImagePicker();
  XFile? image;
  // 打开相机拍摄 或选择相片
  selectCameraOrPhoto(String choice) async {
    image = await _imagePicker.pickImage(
      // ImageSource.gallery：选择相册且只为单张 ImageSource.camera：拍摄
      source: choice == 'photo' ? ImageSource.gallery : ImageSource.camera,
      preferredCameraDevice: CameraDevice.rear,
    );

    if (image != null) {
      tipController.imageUrl!.value = File(image!.path);
      tipController.hasAvatar.value = true;
    }

    print('展示');
    print(tipController.imageUrl);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  void _myDialog() async {
    var oldpwd = TextEditingController();
    var newpwd = TextEditingController();
    var confirmpwd = TextEditingController();

    // 旧密码框验证方法
    void oldPwdMethod() {
      if (oldpwd.text == '') {
        tipController.oldpwdText.value = StringStyles.nulloldpwd.tr;
      } else {
        tipController.oldpwdText.value = '';
      }
    }

    // 新密码框验证方法
    void newPwdMethod() {
      if (confirmpwd.text == '') return;
      if (newpwd.text == '') {
        tipController.tipText.value = StringStyles.nullnewpwd.tr;
      } else if (newpwd.text != confirmpwd.text) {
        tipController.tipText.value = StringStyles.nosamepwd.tr;
      } else {
        tipController.tipText.value = '';
      }
    }

    // 确认密码框验证方法
    void confirmMethod() {
      if (confirmpwd.text == '') {
        tipController.tipText.value = StringStyles.nullconfirmpwd.tr;
      } else if (newpwd.text == '') {
        tipController.tipText.value = StringStyles.nullnewpwd.tr;
      } else if (newpwd.text != confirmpwd.text) {
        tipController.tipText.value = StringStyles.nosamepwd.tr;
      } else {
        tipController.tipText.value = '';
      }
    }

    // 密码一致性提示词
    var result = await showDialog(
        barrierDismissible: true, //表示点击灰色背景的时候是否消失弹出框
        context: context,
        builder: (context) {
          return MyDialog(
            title: StringStyles.changePwd.tr,
            onClosed: () {
              Navigator.of(context).pop();
            },
            content: GestureDetector(
              onTap: () {
                print('关闭键盘');
                FocusManager.instance.primaryFocus?.unfocus();
              },
              child: Container(
                  color: Get.isDarkMode
                      ? const Color.fromARGB(164, 0, 0, 0)
                      : Colors.white,
                  alignment: Alignment.center,
                  padding: const EdgeInsets.only(top: 0, left: 0, right: 0),
                  child: Stack(children: [
                    SizedBox(
                      height: 400,
                      // alignment: const Alignment(0, 0),
                      child: Column(
                        children: [
                          const SizedBox(
                            height: 20,
                          ),
                          SizedBox(
                              width: 320,
                              height: 50,
                              child: Stack(
                                children: [
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                    // row组件本身不能设置高度 只能外套一个有高度的容器 这个属性针对外层容器本row的位置
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      SizedBox(
                                        width: 72,
                                        child:
                                            Text('${StringStyles.oldpwd.tr}：'),
                                      ),
                                      Expanded(
                                        flex: 1,
                                        child: Obx(() => TextField(
                                              controller: oldpwd,
                                              cursorColor:
                                                  ColorStyle.thememode_color,
                                              obscureText: !iconController
                                                  .oldpwdShow
                                                  .value, // 文本隐藏标识，true为*号密码
                                              inputFormatters: [
                                                ///输入长度和格式限制
                                                CustomizedLengthTextInputFormatter(
                                                    16),
                                                CustomizedTextInputFormatter(
                                                  filterPattern:
                                                      RegExp("[a-zA-Z]|[0-9]"),
                                                ),
                                              ],
                                              onChanged: (value) {
                                                oldPwdMethod();
                                              },
                                              decoration: InputDecoration(
                                                // prefixIcon: const Icon(Icons.password_outlined),
                                                hintText: StringStyles
                                                    .typingOldPwd.tr,
                                                hintStyle: const TextStyle(
                                                    color: Colors.grey,
                                                    fontSize: 14),
                                                border: OutlineInputBorder(
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                            40)),
                                              ),
                                            )),
                                      )
                                    ],
                                  ),
                                  Positioned(
                                    right: 0,
                                    child: Obx(() => Visibility(
                                          visible: true && true,
                                          child: IconButton(
                                            icon: Icon(
                                              iconController.oldpwdShow.value
                                                  ? Icons.remove_red_eye
                                                  : Icons.visibility_off,
                                              size: 24,
                                              color: Colors.black,
                                            ),
                                            onPressed: () {
                                              iconController.oldpwdShow.value =
                                                  !iconController
                                                      .oldpwdShow.value;
                                            },
                                          ),
                                        )),
                                  )
                                ],
                              )),
                          const SizedBox(
                            height: 20,
                          ),
                          SizedBox(
                            width: 320,
                            height: 50,
                            child: Stack(
                              children: [
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceEvenly,
                                  // row组件本身不能设置高度 只能外套一个有高度的容器 这个属性针对外层容器本row的位置
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    SizedBox(
                                      width: 72,
                                      child: Text('${StringStyles.newpwd.tr}：'),
                                    ),
                                    Expanded(
                                      flex: 1,
                                      child: Obx(() => TextField(
                                            controller: newpwd,
                                            cursorColor:
                                                ColorStyle.thememode_color,
                                            obscureText: !iconController
                                                .newpwdShow
                                                .value, // 隐藏文本内容，用于密码
                                            inputFormatters: [
                                              ///输入长度和格式限制
                                              CustomizedLengthTextInputFormatter(
                                                  16),
                                              CustomizedTextInputFormatter(
                                                filterPattern:
                                                    RegExp("[a-zA-Z]|[0-9]"),
                                              ),
                                            ],
                                            onChanged: (value) {
                                              newPwdMethod();
                                            },
                                            decoration: InputDecoration(
                                              // prefixIcon: const Icon(Icons.password_outlined),
                                              hintText:
                                                  StringStyles.typingNewPwd.tr,
                                              hintStyle: const TextStyle(
                                                  color: Colors.grey,
                                                  fontSize: 14),
                                              border: OutlineInputBorder(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          40)),
                                            ),
                                          )),
                                    )
                                  ],
                                ),
                                Positioned(
                                  right: 0,
                                  child: Obx(() => Visibility(
                                        visible: true && true,
                                        child: IconButton(
                                          icon: Icon(
                                            iconController.newpwdShow.value
                                                ? Icons.remove_red_eye
                                                : Icons.visibility_off,
                                            size: 24,
                                            color: Colors.black,
                                          ),
                                          onPressed: () {
                                            iconController.newpwdShow.value =
                                                !iconController
                                                    .newpwdShow.value;
                                          },
                                        ),
                                      )),
                                )
                              ],
                            ),
                          ),
                          const SizedBox(
                            height: 20,
                          ),
                          SizedBox(
                            width: 320,
                            height: 50,
                            child: Stack(
                              children: [
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceEvenly,
                                  // row组件本身不能设置高度 只能外套一个有高度的容器 这个属性针对外层容器本row的位置
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    SizedBox(
                                      width: 72,
                                      child: Text(
                                          '${StringStyles.confirmpwd.tr}：'),
                                    ),
                                    Expanded(
                                      flex: 1,
                                      child: Obx(() => TextField(
                                            controller: confirmpwd,
                                            cursorColor:
                                                ColorStyle.thememode_color,
                                            obscureText: !iconController
                                                .confirmpwdShow
                                                .value, // 隐藏文本内容，用于密码
                                            inputFormatters: [
                                              ///输入长度和格式限制
                                              CustomizedLengthTextInputFormatter(
                                                  16),
                                              CustomizedTextInputFormatter(
                                                filterPattern:
                                                    RegExp("[a-zA-Z]|[0-9]"),
                                              ),
                                            ],
                                            onChanged: (value) {
                                              confirmMethod();
                                            },
                                            decoration: InputDecoration(
                                              // prefixIcon: const Icon(Icons.password_outlined),
                                              hintText: StringStyles
                                                  .typingConfirmPwd.tr,
                                              hintStyle: const TextStyle(
                                                  color: Colors.grey,
                                                  fontSize: 14),
                                              border: OutlineInputBorder(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          40)),
                                            ),
                                          )),
                                    )
                                  ],
                                ),
                                Positioned(
                                  right: 0,
                                  child: Obx(() => Visibility(
                                        visible: true && true,
                                        child: IconButton(
                                          icon: Icon(
                                            iconController.confirmpwdShow.value
                                                ? Icons.remove_red_eye
                                                : Icons.visibility_off,
                                            size: 24,
                                            color: Colors.black,
                                          ),
                                          onPressed: () {
                                            iconController
                                                    .confirmpwdShow.value =
                                                !iconController
                                                    .confirmpwdShow.value;
                                          },
                                        ),
                                      )),
                                )
                              ],
                            ),
                          ),
                          Container(
                            margin: const EdgeInsets.only(top: 50),
                            width: 220,
                            child: ElevatedButton(
                                onPressed: () {
                                  if (tipController.oldpwdText.value != '' ||
                                      tipController.tipText.value != '') {
                                    ToastUtils.show(StringStyles.inputError.tr);
                                    return;
                                  }
                                  if (oldpwd.text == '') {
                                    ToastUtils.show(StringStyles.nulloldpwd.tr);
                                    return;
                                  }
                                  if (newpwd.text == '') {
                                    ToastUtils.show(StringStyles.nullnewpwd.tr);
                                    return;
                                  }
                                  if (confirmpwd.text == '') {
                                    ToastUtils.show(
                                        StringStyles.nullconfirmpwd.tr);
                                    return;
                                  }
                                  // 收回键盘
                                  FocusScope.of(context)
                                      .requestFocus(FocusNode());

                                  Request.post(Api.changepwd, {
                                    'uid': userController.userId.value,
                                    'passwordold': oldpwd.text,
                                    'passwordnew': confirmpwd.text
                                  }, success: (String res) async {
                                    if (res.isNotEmpty) {
                                      ToastUtils.show(
                                          StringStyles.pwdUpdateOk.tr);
                                      Navigator.of(context).pop();

                                      // 清除本地缓存
                                      Store store = await Store.getInstance();
                                      bool? clearAll = await store.clearAll();
                                      if (clearAll ?? false) {
                                        Get.offAll(() => const Login());
                                      } else {
                                        print('退出登录失败');
                                      }

                                      // 延迟2s清除全局数据 避免页面展示混乱的
                                      Timer(const Duration(seconds: 2), () {
                                        // 清除全局数据
                                        userController.user.value = {};
                                        userController.userId.value = 0;
                                        userController.userAccount.value = '';
                                        userController.islogin.value = false;
                                      });
                                    }
                                  });
                                },
                                child: Text(StringStyles.confirmSubmit.tr)),
                          ),
                          Container(
                            margin: const EdgeInsets.only(top: 10),
                            width: 220,
                            child: ElevatedButton(
                                onPressed: () {
                                  setState(() {
                                    oldpwd.text = '';
                                    newpwd.text = '';
                                    confirmpwd.text = '';
                                  });
                                },
                                child: Text(StringStyles.resetInput.tr)),
                          )
                        ],
                      ),
                    ),
                    Positioned(
                      left: 84,
                      top: 70,
                      child: Obx(() => Text(
                            tipController.oldpwdText.value,
                            style: const TextStyle(
                                color: Colors.red, fontSize: 14),
                          )),
                    ),
                    Positioned(
                      // alignment: const Alignment(-0.25, 1),
                      left: 84,
                      top: 210,
                      child: Obx(() => Text(
                            tipController.tipText.value,
                            style: const TextStyle(
                                color: Colors.red, fontSize: 14),
                          )),
                    ),
                  ])),
            ),
          );
        });

    // 相当于添加处理模态框关闭事件
    if (result == null) {
      print('模态框关闭');
      // 清空提示词
      tipController.oldpwdText.value = '';
      tipController.tipText.value = '';
      iconController.oldpwdShow.value = false;
      iconController.newpwdShow.value = false;
      iconController.confirmpwdShow.value = false;
    }
  }

  // 更换头像
  void _changeAvatarDialog() async {
    // 重复调用发送图片 并收集结果到传递的数组
    _repeatedlyRequest(String url, context) async {
      Future<dio_package.FormData> createFormData() async {
        String fileName = url.split('/').last;
        return dio_package.FormData.fromMap({
          'date': DateTime.now().toIso8601String(),
          'imgFile': await dio_package.MultipartFile.fromFile(
            url,
            filename: fileName,
          ),
        });
      }

      Map res =
          await Request2.post<Map>(Api.uploadFile, await createFormData());
      // print(res);
      // print('图片结果');
      if (res['img'] != '') {
        bool setAvatarRes = await Request2.post<bool>(Api.setavatar,
            {'uid': userController.userId.value, 'img': res['img']});
        print('setAvatarRes');
        print(setAvatarRes);

        if (setAvatarRes) {
          Map myinfo = await Request2.post<Map>(Api.myinfo, {
            'uid': userController.userId.value,
          });
          print('myinfo');
          print(myinfo);

          if (myinfo['name'] != '') {
            userController.user.value = myinfo;
            Store store = await Store.getInstance();
            await store.saveMap('user', myinfo);
            Navigator.of(context).pop('成功修改');
            ToastUtils.show(StringStyles.avatarUpdateOk.tr);
            tipController.imageUrl!.value = File('');
            tipController.hasAvatar.value = false;
          }
        }
      }
    }

    var result = await showDialog(
        barrierDismissible: true, //表示点击灰色背景的时候是否消失弹出框
        context: context,
        builder: (context) {
          return MyDialog(
              title: StringStyles.changeAvatarTip.tr,
              onClosed: () {
                Navigator.of(context).pop();
              },
              content: Center(
                child: Column(
                  children: [
                    const SizedBox(
                      height: 40,
                    ),
                    Obx(() => tipController.hasAvatar.value
                        ? Stack(
                            children: [
                              GestureDetector(
                                onTap: () {
                                  Get.toNamed('/photopreview', arguments: {
                                    'imageList': [image!.path],
                                    'curIndex': 0
                                  });
                                },
                                child: Hero(
                                  tag: "img0",
                                  child: Align(
                                    alignment: const Alignment(0, 0),
                                    child: Container(
                                      width: 180,
                                      height: 180,
                                      alignment: const Alignment(0, 0),
                                      decoration: BoxDecoration(
                                          border: Border.all(
                                            width: 1,
                                            color: Colors.black12,
                                          ),
                                          borderRadius:
                                              BorderRadius.circular(90)
                                          // color: Colors.red,
                                          ),
                                      child: Obx(() => CircleAvatar(
                                            radius: 90,
                                            backgroundImage: FileImage(
                                                tipController.imageUrl!.value),
                                          )),
                                    ),
                                  ),
                                ),
                              ),
                              Positioned(
                                  top: 0,
                                  right: 70,
                                  child: SizedBox(
                                    width: 30,
                                    height: 30,
                                    child: ElevatedButton(
                                        style: ElevatedButton.styleFrom(
                                            padding: EdgeInsets.zero,
                                            backgroundColor: Colors.white70),
                                        iconAlignment: IconAlignment.end,
                                        onPressed: () {
                                          print('删除');
                                          tipController.imageUrl!.value =
                                              File('');
                                          tipController.hasAvatar.value = false;
                                        },
                                        child: const Icon(
                                          Icons.delete,
                                          size: 20,
                                          color:
                                              Color.fromARGB(166, 244, 76, 54),
                                        )),
                                  )),
                            ],
                          )
                        : SizedBox(
                            width: 180,
                            height: 180,
                            child: ElevatedButton(
                                onPressed: () async {
                                  var res = await _showbottomDialog();
                                  print('加图');
                                  print(res);
                                },
                                style: ButtonStyle(
                                  shape: WidgetStateProperty.all(
                                    RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(90),
                                    ),
                                  ), // 去除圆角
                                ),
                                child: const Icon(
                                  Icons.add,
                                  size: 50,
                                )),
                          )),
                    Container(
                      margin: const EdgeInsets.only(top: 100),
                      width: 220,
                      child: ElevatedButton(
                          onPressed: () {
                            _repeatedlyRequest(image!.path, context);
                          },
                          child: Text(StringStyles.confirmSubmit.tr)),
                    )
                  ],
                ),
              ));
        });

    // 相当于添加处理模态框关闭事件
    if (result == null) {
      print('改头像模态框关闭');
      tipController.imageUrl!.value = File('');
      tipController.hasAvatar.value = false;
    }
  }

  // 底部弹出框
  _showbottomDialog() async {
    var result = await showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
            height: 200,
            child: Stack(
              children: [
                Align(
                  alignment: const Alignment(0, -0.8),
                  child: SizedBox(
                    width: 240,
                    child: ElevatedButton(
                      style: ButtonStyle(
                        backgroundColor: WidgetStateProperty.all(Colors.blue),
                        foregroundColor: WidgetStateProperty.all(Colors.white),
                      ),
                      onPressed: () async {
                        selectCameraOrPhoto('photo');
                        Navigator.pop(context, '选择照片');
                      },
                      child: Text(StringStyles.selectPhoto.tr),
                    ),
                  ),
                ),
                Align(
                  alignment: const Alignment(0, -0.15),
                  child: SizedBox(
                    width: 240,
                    child: ElevatedButton(
                      style: ButtonStyle(
                        backgroundColor: WidgetStateProperty.all(Colors.blue),
                        foregroundColor: WidgetStateProperty.all(Colors.white),
                      ),
                      onPressed: () async {
                        selectCameraOrPhoto('camera');

                        Navigator.pop(context, '拍摄');
                      },
                      child: Text(StringStyles.camera.tr),
                    ),
                  ),
                ),
                Align(
                  alignment: const Alignment(0, 0.7),
                  child: SizedBox(
                    width: 240,
                    child: ElevatedButton(
                      onPressed: () async {
                        Navigator.pop(context, '取消');
                      },
                      child: Text(StringStyles.cancel.tr),
                    ),
                  ),
                ),
              ],
            ),
          );
        });
    return result;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(StringStyles.personalcenter.tr),
        backgroundColor: Colors.blue,
      ),
      body: Center(
        child: Stack(
          children: [
            Align(
              alignment: Alignment.center,
              // color: Colors.red,
              child: SizedBox(
                width: 300,
                child: Column(
                  children: [
                    const SizedBox(
                      height: 50,
                    ),
                    GestureDetector(
                      onTap: () {
                        print('修改头像');
                        _changeAvatarDialog();
                      },
                      child: ClipOval(
                        child: Obx(() => Image.network(
                              userController.user['avatar'],
                              width: 100,
                              height: 100,
                              fit: BoxFit.cover,
                            )),
                      ),
                    ),
                    const SizedBox(
                      height: 10,
                    ),
                    Text(StringStyles.changeAvatar.tr),
                    const SizedBox(
                      height: 40,
                    ),
                    SizedBox(
                      width: 300,
                      height: 40,
                      child: Row(
                        children: [
                          const SizedBox(
                            width: 16,
                          ),
                          SizedBox(
                            width: 120,
                            child: Text(
                              '${StringStyles.nickname.tr}：',
                              style: const TextStyle(fontSize: 18),
                            ),
                          ),
                          Expanded(
                              flex: 1,
                              child: Obx(() => Text(
                                    "${userController.user['name']}",
                                    textAlign: TextAlign.start,
                                    style: const TextStyle(fontSize: 18),
                                  )))
                        ],
                      ),
                    ),
                    const Divider(),
                    SizedBox(
                      width: 300,
                      height: 40,
                      child: Row(
                        children: [
                          const SizedBox(
                            width: 16,
                          ),
                          SizedBox(
                            width: 120,
                            child: Text(
                              '${StringStyles.account.tr}：',
                              style: const TextStyle(fontSize: 18),
                            ),
                          ),
                          Expanded(
                              flex: 1,
                              child: Obx(() => Text(
                                    "${userController.userAccount}",
                                    textAlign: TextAlign.start,
                                    style: const TextStyle(fontSize: 18),
                                  )))
                        ],
                      ),
                    ),
                    const Divider(),
                    SizedBox(
                      width: 300,
                      height: 40,
                      child: Row(
                        children: [
                          const SizedBox(
                            width: 16,
                          ),
                          SizedBox(
                            width: 120,
                            child: Text(
                              '${StringStyles.mobile.tr}：',
                              style: const TextStyle(fontSize: 18),
                            ),
                          ),
                          Expanded(
                              flex: 1,
                              child: Obx(() => Text(
                                    "${userController.user['mobile']}",
                                    textAlign: TextAlign.start,
                                    style: const TextStyle(fontSize: 18),
                                  )))
                        ],
                      ),
                    ),
                    const Divider(),
                  ],
                ),
              ),
            ),
            Align(
              alignment: Alignment(0, 0.9),
              child: GestureDetector(
                onTap: () {
                  print('修改密码');
                  _myDialog();
                },
                child: Text(StringStyles.changePwd.tr),
              ),
            )
          ],
        ),
      ),
    );
  }
}
